﻿using EShopV20.Models;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EShopV20.Areas.Adm.Controllers
{
    public class RoleController : Controller
    {
        ApplicationDbContext db = new ApplicationDbContext();
        //
        // GET: /Adm/IdentityRole/
        public ActionResult Index()
        {
            ViewBag.Roles = db.Roles;

            var model = new IdentityRole();
            return View(model);
        }

        public ActionResult Insert(IdentityRole model)
        {
            try
            {
                db.Roles.Add(model);
                db.SaveChanges();

                /*
                 * Bổ sung Permission cho Role mới nhập vào
                 */
                var eshopdb = new EShopV20DbContext();
                foreach (var wa in eshopdb.WebActions)
                {
                    var perm = new Permission
                    {
                        Allow=false,
                        RoleId=model.Id,
                        WebActionId=wa.Id
                    };
                    eshopdb.Permissions.Add(perm);
                    eshopdb.SaveChanges();
                }
                
                
                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                ViewBag.Roles = db.Roles;
                return View("Index", model);
            }
        }

        public ActionResult Update(IdentityRole model)
        {
            try
            {
                db.Entry(model).State = EntityState.Modified;
                db.SaveChanges();
                ModelState.AddModelError("", "Cập nhật thành công !");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
            }
            ViewBag.Roles = db.Roles;
            return View("Index", model);
        }

        public ActionResult Delete(String Id)
        {
            var model = db.Roles.Find(Id);
            db.Roles.Remove(model);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Edit(String Id)
        {
            var model = db.Roles.Find(Id);
            ViewBag.Roles = db.Roles;
            return View("Index", model);
        }
	}
}